// Package cmd
/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

// rootCmd represents the base command when called without any subcommands
var (
	// Used for flags:
	cfgFile      string
	myFlag       bool
	MyFlagString string

	rootCmd = &cobra.Command{
		Use: "demo",

		Short: "this my hello world application, cmd: demo",
		Long: `this my hello world application. For example:

这些英文实在是太烦人了，于是我用中文写一篇demo的命令介绍.`,
		//Uncomment the following line if your bare application
		//has an action associated with it:


		//Run: func(cmd *cobra.Command, args []string) {
		//	for _, arg := range args {
		//		println("myFlagString: "+myFlagString+", 我通过println输出东西。: ")
		//		println(arg)
		//	}
		//},
	}
)

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	//cobra.OnInitialize(initConfig)
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.
	// the upon words means the 持久性，一次编译全局使用。
	//rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.test.yaml)")
	rootCmd.PersistentFlags().StringP("author", "a", "cheng jiang", "author name for copyright")
	rootCmd.PersistentFlags().StringVarP(&MyFlagString, "myFlagString", "s", "cheng jiang create it here", "this is my first flag string")
	//rootCmd.PersistentFlags().Bool("useViper", true, "use viper for configuration here.")

	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	rootCmd.Flags().BoolVarP(&myFlag, "myFlag", "m", false, "this is my first flag bool")
}

func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		// so viper means: 毒蛇？
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := os.UserHomeDir()
		cobra.CheckErr(err)

		// Search config in home directory with name ".cobra" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigType("yaml")
		viper.SetConfigName(".cobra")
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
